# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: client_view.py
Author: kij
Create Date: 2021/3/2
-------------------------------------------------
"""
import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

import client_interface
from conn import setting


# 用户端发送


def auth(my_client):
	"""
	验证用户名密码
	:param my_client: 链接对象
	:return:
	"""
	count = 0

	while count < 3:
		user_name = input("请输入用户名: ").strip()
		if not user_name:
			continue
		user_password = input("输入用户密码: ").strip()
		if not user_password:
			continue
		# 用于生成json数据传递给服务器 成功的话返回的是链接对象类失败返回提示信息
		result_client, result = client_interface.auth(my_client, user_name, user_password)
		if switch_hint(result_client, result):
			return True
		count += 1


def close_net(conn):
	if client_interface.close_net(conn):
		print('退出成功'.center(50, '*'))


def switch_hint(app_client, message):
	"""根据不同类型消息来显示不同的提示语句"""
	# 登录方法提示
	print(message.get('msg'))
	if message.get('action_type') in func_dict:
		result = func_dict[message.get('action_type')](app_client, message)
		return result
	else:
		return False


def unfinished_file_check(app_client):
	"""检查shelve db ，把为正常传完的文件列表打印，按用户的指令决定是否重传"""

	if list(app_client.shelve_obj.keys()):
		for index, abs_file in enumerate(app_client.shelve_obj.keys()):
			# 已经下载了的文件大小
			print(app_client.shelve_obj[abs_file][1])
			received_file_size = os.path.getsize(app_client.shelve_obj[abs_file][1])
			print(
				"%s. %s    %s    %s   %s" % (
					index, abs_file, app_client.shelve_obj[abs_file][0],
					received_file_size, received_file_size / app_client.shelve_obj[abs_file][0] * 100
				))
		while True:
			choice = input("选择的未下载的文件:").strip()
			if not choice: continue
			if choice.isdecimal():
				choice = int(choice)
				if choice >= 0 and choice <= index:
					selected_file = list(app_client.shelve_obj.keys())[choice]
					# 拿到已经接收的文件大小
					already_received_size = os.path.getsize(app_client.shelve_obj[selected_file][1])
					re_file_dict = {
						'already_received_size': already_received_size,
						# 服务器文件路径
						'file_path': selected_file,

					}
					message = client_interface.re_get_file(app_client,re_file_dict)
					if message.get('code') == 200:
						print()
						break
					else:
						print(message.get('msg'))
						return False


def logon(app_client, message):
	if message.get('code') == 200:
		app_client.username = message.get('username')
		app_client.current_dir = message.get('current_dir')
		app_client.hint = 'bogon:%s %s$ ' % (app_client.username, app_client.current_dir)
		return True
	else:
		return False


def down_file(app_client, message):
	if message.get('code') == 200:
		print('下载完成')
		return True
	else:
		return False


def ls(app_client, message):
	if message.get('code') == 200:
		print(message['data'])
		return True
	else:
		return False


def cd(app_client, message):
	if message.get('code') == 200:
		# 设置当前目录
		app_client.current_dir = message.get('current_dir')
		app_client.hint = 'bogon:%s %s$ ' % (app_client.username, app_client.current_dir)
		return True
	else:
		return False


def _dir(app_client, message):
	if message.get('code') == 200:
		print(message['data'])
		return True
	else:
		return False


def _mkdir(app_client, message):
	if message.get('code') == 200:
		return True
	else:
		return False


def update_file(app_client, message):
	if message.get('code') == 200:
		return True
	else:
		return False


func_dict = {
	'logon': logon,
	'down_file': down_file,
	'ls': ls,
	'cd': cd,
	'dir': _dir,
	'mkdir': _mkdir,
	'update_file': update_file
}


def run():
	print("""客户端启动成功""")

	# parser = optparse.OptionParser()
	# parser.add_option("-s", "--server", dest="server", help="服务器IP地址")
	# parser.add_option("-P", "--port", type='int', dest="port", help="服务器端口")
	# parser.add_option("-u", "--username", dest="username", help="用户姓名")
	# parser.add_option("-p", "--password", dest="password", help="用户密码")
	# options, args = parser.parse_args()
	# has_ip, hint = client_interface.argv_verification(options.server, options.port)
	# 启用链接
	is_connect, my_client = client_interface.argv_verification(setting.HOST, setting.PORT)
	if not is_connect:
		print(my_client)
	else:
		# 登录后台服务器开始交互
		has_account = auth(my_client)
		if not has_account:
			return has_account
		else:
			# 检查文件是否下载完 继续下载源文件
			unfinished_file_check(my_client)
			while True:
				try:
					input_msg = input(my_client.hint)
					if input_msg.upper() == 'Q':
						close_net(my_client)
						break
					# 获取数据然后传入  链接对象类 app_client
					result = client_interface.switch_func(input_msg, my_client)
					switch_hint(my_client, result)
				except KeyboardInterrupt as e:
					print(".", e)


# 拿到返回数据进行显示处理


if __name__ == "__main__":
	run()
